package q4

import (
	"errors"
	"sync"
)

/**
 * @Description
 * @Author huran
 * @Date
 * @Param
 * @return
 **/

type Broker struct {
	mutex sync.RWMutex
	chans []chan Msg
}

func (b *Broker) Send(m Msg) error {
	b.mutex.RLock()
	defer b.mutex.RUnlock()
	for _, ch := range b.chans {
		select {
		case ch <- m:
		default:
			return errors.New("消息对了已经满了")
		}
	}
	return nil
}
func (b *Broker) Subscribe(cap int) (<-chan Msg, error) {
	res := make(chan Msg, cap)
	b.mutex.RLock()
	defer b.mutex.RUnlock()
	b.chans = append(b.chans, res)
	return res, nil
}
func (b *Broker) Close() error {
	b.mutex.RLock()
	chans := b.chans
	b.chans = nil
	defer b.mutex.RUnlock()
	//避免了重复调用Close的问题
	for _, ch := range chans {
		close(ch)
	}
	return nil
}

type Msg struct {
	Content string
}

// Broker2 遍历消费者
type Broker2 struct {
	mutex     sync.RWMutex
	consumers []func(msg Msg)
}

func (b *Broker2) Send(m Msg) error {
	b.mutex.RLock()
	defer b.mutex.RUnlock()
	for _, c := range b.consumers {
		go c(m)
	}
	return nil
}
func (b *Broker2) Subscribe(cb func(m Msg)) error {
	b.mutex.RLock()
	defer b.mutex.RUnlock()
	b.consumers = append(b.consumers, cb)
	return nil
}
